#!/usr/bin/env bash
# Copyright (c) 2024 Pekka Jääskeläinen / Intel Finland Oy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# A script to test the parallel.bc output using LLVM's FileCheck.
#
# Usage:
#
# run-and-check-llvm-ir PATH/TO/llvm-FileCheck PATH/TO/llvm-dis PATH/TO/FileCheck-file PATH/TO/opencl-app ARGS
#
# It then runs the given OpenCL application, letting it dump the final
# vectorized work-group function in parallel.bc, which is then checked using
# LLVM's FileCheck with the verification checks read from the given file.
# This thus works only for cases when the application compiles and launches
# a single kernel with a single local size. No error checking / user
# friendliness is done by the script.

LLVM_FILECHECK=$1
LLVM_DIS=$2
CHECK_FILE=$3
shift 3
APP_CMD=$@

export POCL_KERNEL_CACHE=1
export POCL_CACHE_DIR=$(mktemp -d /tmp/pocl-lit-test-XXXXXXXX)
export POCL_LEAVE_KERNEL_COMPILER_TEMP_FILES=1

$APP_CMD || exit 1

BC_FILES=$(find $POCL_CACHE_DIR -name parallel.bc)
LL_FILE=$POCL_CACHE_DIR/parallel-bcs-to-filecheck.ll

for BC_FILE in $BC_FILES
do
   echo "; $BC_FILE" >> $LL_FILE
   $LLVM_DIS $BC_FILE -o - >> $LL_FILE
done

cat $LL_FILE | $LLVM_FILECHECK $CHECK_FILE
RET=$?

trap 'rm -fr $POCL_CACHE_DIR' EXIT

if test $RET -eq 0;
then
    echo LLVM IR checks OK.
    exit 0
else
    cat $LL_FILE
    echo LLVM IR checks FAIL.
    exit 1
fi
